PATH Environment Variable on Linux

Table of Contents


Peeking behind the curtain

The $PATH environment variable allows for all kinds of commands on your linux system to be accessable from anywhere. If you take a look inside, you’ll find it’s just a collection of paths seperated by a colon:

echo $PATH
# OUTPUT: /usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

When you run a command in the command line you really just run a little program. The $PATH variable is your system’s way of knowing where to look for those programs so you have the convenience of running them from anywhere on your system.

Using it to your advantage

This is where the real fun begins!

If you want to make one of your programs or scripts available from anywhere, all you have to do is to add it to your $PATH variable. Now, there are two ways of going about this.

Temporary

If you haven’t worked with environment variables before, this is how you define one in the command line:

var_name=value

Easy right? If you want to use it anywhere now you can simply write $var_name and it will be replaced with the variables value.
A very simple example is echo:

echo $var_name
# Output: value

You can do the same with the $PATH environment variable to add a directory path to it.

BE CAREFUL THOUGH! You do not want to overwrite the whole variable! Whatever path you write after the equals sign follow it up with :$PATH

That having said, let’s suppose you have a scripts folder in your home directory and want to add it to the $PATH variable. You may do it like so:

PATH=/home/pantonius/scripts/:$PATH

Where “pantonius” should be your username.
Now you have access to all of your valuable scripts from anywhere on the system!

Notice though: The path to your home directory is only in the $PATH variable until you reboot your system. After that it will only contain the usual paths once again.

Permanent

To make the change to the $PATH variable permanent you may edit the .bashrc file in your home directory.

ONCE AGAIN: BE CAREFUL NOT TO OVERWRITE YOUR PATH VARIABLE PERMANENTLY

sudo nano ~/.bashrc

Scroll to the very bottom of the file and add the variable definition from before:

PATH=/home/pantonius/scripts/:$PATH

Et voila! Now you can run all of your favourite scripts as if they were always a part of your system!